

console.log("my stock ajax")


setInterval(() => {
    location.reload();
}, 3600000);


var api1_fail_number = 0;
var api2_fail_number = 0;
var api3_fail_number = 0;
var success_time = 0;

chrome.runtime.onMessage.addListener(async (msg, sender) => {

    console.log(msg);
    if(api1_fail_number <=3){
        getDataByApiByProductRealTime(msg);
    }else if(api2_fail_number <=3){
        getDataByApiDetailRealTime(msg);
    }else if(api3_fail_number <=5){
        getDataByApiStaticRealTime(msg);
    }else{
        location.reload();

        /*
        console.log("sheinblock_yuenanstock");
        fail_number = 0;
        var type = "sheinblock_yuenanstock";
        chrome.runtime.sendMessage({ data: {type }, close: false });
        setTimeout(() => {
            location.reload()
        },5000);
        return;*/
    }
})


function getDataByApiByProductRealTime(msg){
    console.log("start api 1");
    var goods_id = msg.data.goods_id;
    const url = 'https://my.shein.com/api/productInfo/realTimeData/query?_ver=1.1.8&_lang=en'; // 替换为您的接口地址
    const payload = {
        goods_id: msg.data.goods_id,
        mallCode: "1",
        tsp: {},
        specialSceneType: 0,
        tags: [
            { tagId: "2422", tagValueId: ["9680"] },
            { tagId: "2423", tagValueId: ["83281"] },
            { tagId: "3199", tagValueId: ["502"] },
            { tagId: "3864", tagValueId: ["12.72"] },
            { tagId: "3865", tagValueId: ["12.64"] },
            { tagId: "3866", tagValueId: ["12.64"] },
            { tagId: "4015", tagValueId: ["12.74"] },
            { tagId: "4016", tagValueId: ["12.74"] },
            { tagId: "4017", tagValueId: ["12.74"] },
            { tagId: "4018", tagValueId: ["2"] },
            { tagId: "4448", tagValueId: ["67"] },
            { tagId: "4607", tagValueId: ["2388"] },
            { tagId: "60007749", tagValueId: ["1"] },
            { tagId: "100000112", tagValueId: [1] },
            { tagId: "100000317", tagValueId: [1] },
            { tagId: "100000444", tagValueId: [1] },
            { tagId: "100000445", tagValueId: [1] },
            { tagId: "600015000", tagValueId: ["1"] },
            { tagId: "600029050", tagValueId: ["1"] },
            { tagId: "600137885", tagValueId: ["1"] }
        ],
        transportTypes: ["urgent_express"]
    };

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => {
            if (!response.ok) {
                api1_fail_number++;
                console.log("api1_fail_number:"+api1_fail_number);
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();

        })
        .then(data => {
            api1_fail_number = 0;
            var jsonObject  = data;
            var sku_list = jsonObject['data']['productInfo']['attrSizeList']['sale_attr_list'][goods_id]['sku_list'];
            //console.log(sku_list);

            var stock_map = {};
            var index = 0;
            var price = jsonObject['data']['productInfo']['getPrice']['salePrice']['amount'];
            sku_list.forEach((item) => {
                if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                    stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
                }else{
                    stock_map[index] = item['stock'];
                }
                index++;

            })

            var type = "sheinstock_my";
            var id = msg.data.id;
            console.log(id);
            console.log(stock_map);
            console.log(price);
            chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });


        })
        .catch(error => {
            console.error('Error:', error);
            api1_fail_number++;
            console.log("api1_fail_number:"+api1_fail_number);
        });
}




function getDataByApiStaticRealTime(msg){
    console.log("start api 3");
    var url = "https://my.shein.com/bff-api/product/get_goods_detail_static_data_v2?_ver=1.1.8&_lang=en&goods_id="+msg.data.goods_id+"&mall_code=1&isUserSelectedMallCode=0&isHideEstimatePriceInfo=0&specialSceneType=0";
    fetch(url, {
        method: 'GET',
        headers: {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'anti-in': '0_1.9.1_c38d61_-qx5b0yIhYmNyQg4_nzJw02_XsG7Wbct9SKxL8BesDsAtw5l6XjE4uY2weB9dAatfxMSTdlKbd01lOIVfhNNpdD137c835Lx4N4DCfMSfp66DcYAsPXeyIXkj6hz0reu9PPJ-i9Ry-ZcN2QH_fSWLo5hd5uQECpV0q-zBPYRkrx2LUddIH1SEyjz9DNwu173w-XOcJ0sVk_ubuqPT4t3HK7g-8SiJodsQcItiljQVsOCayA9OoYE14OarnEA2HZXsIqKvxi7aidKvdwY7KteHbcLfxjF2_GwfxFfTY9csb6o0b6HX9MvXvcP05Ho2pepxfZ3XTeqw4PYkyHkKqVDxqBwg1xSJKlEOKyXD3SkCaGcVNrmEfP8_6VioIYou7MCZ0TcH6iVDiN5q2AbhJ1XshURP7yOqnZLmjdf8G2l_XfOQ3SHgIIQlG9JFYKoNkZ2MjKdquUeEpPjJ5pR_aH1QrYgeHv9z3AWK2jbjQ4bsfbO0uM_4ZK_iI_qGhaC_QRrOa9RCu_aG2ilaoiDocXnrKv5jUamfWt-IySkyjAikHFo0rybUKZehMiIhoRoTWfeJSE62J0vRjR76_TgrG1XerIZyAG6HNa-Ny1wi_3ZRqsA4RrM5WWmYIrH_MfsI2q1waNo1JJZO9EiXgKFd3kCQJseDQFFf-7CR8uJDYYd7C9i0iGwk8gOyXmswakoO2qKQD_ZaLia0mfiHOd4kXSAfJqNNyqG_vTjeSEXNmZRwN4cGoln1A8FkBEKsMUc6uY7m',
            'armortoken': 'T0_3.3.0_HrzEkoY1JjaE3mp_fOTINtzBb-h-EkHI0vvSoOmZuZcgwjbqAfmTkQm-fjEVe-gXeN9a2jl02nli0HXVAdgRVvXqDIfiPnUWKtA5HvEwH3RAxPc4sBDMcXOJpkm0tW_mqFiuAGw6zghfuIDcFn_Vuyd5REj4JUH6F8gsPL3qzJjakISTWpoJfszsJHKxxwy7_1747379001280',
            'priority': 'u=1, i',
            'referer': 'https://s1.shein.com/',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            // Add other needed headers from the second request here as necessary
        },
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            api3_fail_number = 0;
            //console.log(data);
            doWitdhDataJob(data,msg.data.id);
        })
        .catch(error => {
            api3_fail_number ++;
            console.log("api3_fail_number:"+api3_fail_number);
        });
}

function getDataByApiDetailRealTime(msg){
    console.log("start api 2");
    var url = "https://my.shein.com/bff-api/product/get_goods_detail_realtime_data?_ver=1.1.8&_lang=en&goods_id=" + msg.data.goods_id + "&mallCode=1&isUserSelectedMallCode=0&isQueryIsPaidMember=1&isQueryCanTrail=0&isHideEstimatePriceInfo=0&specialSceneType=0&countryId=226";
    fetch(url, {
        method: 'GET',
        headers: {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'anti-in': '0_1.9.1_c38d61_-qx5b0yIhYmNyQg4_nzJw02_XsG7Wbct9SKxL8BesDsAtw5l6XjE4uY2weB9dAatfxMSTdlKbd01lOIVfhNNpdD137c835Lx4N4DCfMSfp66DcYAsPXeyIXkj6hz0reu9PPJ-i9Ry-ZcN2QH_fSWLo5hd5uQECpV0q-zBPYRkrx2LUddIH1SEyjz9DNwu173w-XOcJ0sVk_ubuqPT4t3HK7g-8SiJodsQcItiljQVsOCayA9OoYE14OarnEA2HZXsIqKvxi7aidKvdwY7KteHbcLfxjF2_GwfxFfTY9csb6o0b6HX9MvXvcP05Ho2pepxfZ3XTeqw4PYkyHkKqVDxqBwg1xSJKlEOKyXD3SkCaGcVNrmEfP8_6VioIYou7MCZ0TcH6iVDiN5q2AbhJ1XshURP7yOqnZLmjdf8G2l_XfOQ3SHgIIQlG9JFYKoNkZ2MjKdquUeEpPjJ5pR_aH1QrYgeHv9z3AWK2jbjQ4bsfbO0uM_4ZK_iI_qGhaC_QRrOa9RCu_aG2ilaoiDocXnrKv5jUamfWt-IySkyjAikHFo0rybUKZehMiIhoRoTWfeJSE62J0vRjR76_TgrG1XerIZyAG6HNa-Ny1wi_3ZRqsA4RrM5WWmYIrH_MfsI2q1waNo1JJZO9EiXgKFd3kCQJseDQFFf-7CR8uJDYYd7C9i0iGwk8gOyXmswakoO2qKQD_ZaLia0mfiHOd4kXSAfJqNNyqG_vTjeSEXNmZRwN4cGoln1A8FkBEKsMUc6uY7m',
            'armortoken': 'T0_3.3.0_HrzEkoY1JjaE3mp_fOTINtzBb-h-EkHI0vvSoOmZuZcgwjbqAfmTkQm-fjEVe-gXeN9a2jl02nli0HXVAdgRVvXqDIfiPnUWKtA5HvEwH3RAxPc4sBDMcXOJpkm0tW_mqFiuAGw6zghfuIDcFn_Vuyd5REj4JUH6F8gsPL3qzJjakISTWpoJfszsJHKxxwy7_1747379001280',
            'priority': 'u=1, i',
            'referer': 'https://s1.shein.com/',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            // Add other needed headers from the second request here as necessary
        },
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            api2_fail_number = 0;
            doWitdhDataJob(data,msg.data.id);
        })
        .catch(error => {
            api2_fail_number ++;
            console.log("api2_fail_number:"+api2_fail_number);

     });
}



function doWitdhDataJob(jsonObject,id){

    if(jsonObject['code']=="200301"){
        var type = "sheindetaildel";
        var data={}
        data.id = id
        console.log(data);
        chrome.runtime.sendMessage({ data: {type,data }, close: false })

    }else if(jsonObject['info']['saleAttr'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list']){
        var sku_list = jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list'];
        console.log(sku_list);

        var stock_map = {};
        var index = 0;
        sku_list.forEach((item) => {
            if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
            }else{
                stock_map[index] = item['stock'];
            }
            index++;

        })

        var price = jsonObject['info']['priceInfo']['salePrice']['amount'];

        var type = "sheinstock_my";
        console.log(id);
        console.log(stock_map);
        console.log(price);
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });

    }else if(jsonObject['info']['productInfo']['stock']==0){
        var type = "sheinstock_my";
        console.log('sheinstock send no stock.');
        var stock_map = {};
        stock_map[0] = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });
    }

    console.log(stock_map);
}







